//
//  SendMBCodeViewController.m
//  Beauty
//
//  Created by Snow on 16/8/30.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "SendMBCodeViewController.h"
#import "GXMacro.h"
#import "GXNetWorkingParser.h"
#import "MyViewController.h"
#import "ZWYNetTool.h"
@interface SendMBCodeViewController ()
@property (nonatomic, strong) UITextField *textOfCode;
@property (nonatomic, strong) UIButton *buttonOfTime;
@end

@implementation SendMBCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"login"]];
    //logo_image
    UIImageView *imageOfLogo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"椭圆-1"]];
    [self.view addSubview:imageOfLogo];
    [imageOfLogo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.centerY.mas_equalTo(self.view.mas_centerY).multipliedBy(0.4);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.5);
        make.height.mas_equalTo(self.view.mas_width).multipliedBy(0.3);
    }];
    
    //关闭页面按钮
    UIButton *buttonOfClose = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:buttonOfClose];
    [buttonOfClose setBackgroundImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [buttonOfClose mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).mas_equalTo(50);
        make.right.mas_equalTo(self.view.mas_right).mas_equalTo(-20);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
    [buttonOfClose addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *labelOfSend = [[UILabel alloc] init];
    [self.view addSubview:labelOfSend];
    labelOfSend.text = [NSString stringWithFormat:@"我们已经发送验证短信到 %@", _stringOfPhone];
    labelOfSend.textColor = [UIColor whiteColor];
    labelOfSend.font = [UIFont systemFontOfSize:10];
    [labelOfSend mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(imageOfLogo.mas_bottom).mas_equalTo(50);
        make.left.mas_equalTo(imageOfLogo.mas_left).mas_equalTo(-15);
        make.right.mas_equalTo(imageOfLogo.mas_right).mas_equalTo(15);
        make.height.mas_equalTo(30);
    }];
    labelOfSend.numberOfLines = 0;
    
    UIView *viewOfText = [[UIView alloc] init];
    viewOfText.backgroundColor = [UIColor colorWithWhite:0.702 alpha:0.500];
    viewOfText.layer.masksToBounds = YES;
    viewOfText.layer.cornerRadius = 10;
    viewOfText.layer.borderColor = [[UIColor whiteColor] CGColor];
    viewOfText.layer.borderWidth = 1;
    [self.view addSubview:viewOfText];
    
    [viewOfText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(labelOfSend.mas_bottom).mas_equalTo(30);
        make.left.mas_equalTo(labelOfSend.mas_left);
        make.right.mas_equalTo(labelOfSend.mas_right);
        make.height.mas_equalTo(20);
    }];
    self.textOfCode = [[UITextField alloc] init];
    [self.view addSubview:self.textOfCode];
    self.textOfCode.placeholder = @"请输入验证码";
    [self.textOfCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(labelOfSend.mas_bottom).mas_equalTo(30);
        make.left.mas_equalTo(labelOfSend.mas_left).mas_equalTo(10);
        make.right.mas_equalTo(labelOfSend.mas_right).mas_equalTo(-5);
        make.height.mas_equalTo(20);
    }];
    self.textOfCode.font = [UIFont systemFontOfSize:10];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];//新建可变字典
    dict[NSForegroundColorAttributeName] = [UIColor whiteColor];//设置颜色属性
    NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:self.textOfCode.placeholder attributes:dict];
    [self.textOfCode setAttributedPlaceholder:attribute];
    //1分倒计时按钮
    self.buttonOfTime = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.view addSubview:self.buttonOfTime];
    self.buttonOfTime.layer.masksToBounds = YES;
    self.buttonOfTime.layer.cornerRadius = 10;
    self.buttonOfTime.layer.borderWidth = 1;
    self.buttonOfTime.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.buttonOfTime.backgroundColor = [UIColor colorWithWhite:0.000 alpha:0.728];
    [self.buttonOfTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(80);
        make.top.mas_equalTo(viewOfText.mas_bottom).mas_equalTo(30);
        make.height.mas_equalTo(20);
    }];
    [self.buttonOfTime setTitle:@"重发" forState:UIControlStateNormal];
    self.buttonOfTime.tintColor = [UIColor whiteColor];
    self.buttonOfTime.titleLabel.font = [UIFont systemFontOfSize:10];
    [self.buttonOfTime addTarget:self action:@selector(reGet:) forControlEvents:UIControlEventTouchUpInside];
    //下一步按钮
    UIButton *buttonOfNext = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.view addSubview:buttonOfNext];
    buttonOfNext.layer.masksToBounds = YES;
    buttonOfNext.layer.cornerRadius = 10;
    buttonOfNext.layer.borderWidth = 1;
    buttonOfNext.layer.borderColor = [[UIColor whiteColor] CGColor];
    buttonOfNext.backgroundColor = [UIColor colorWithWhite:0.902 alpha:0.801];
    [buttonOfNext mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(viewOfText.mas_left);
        make.right.mas_equalTo(viewOfText.mas_right);
        make.top.mas_equalTo(self.buttonOfTime.mas_bottom).mas_equalTo(30);
        make.height.mas_equalTo(20);
    }];
    buttonOfNext.tintColor = [UIColor whiteColor];
    buttonOfNext.titleLabel.font = [UIFont systemFontOfSize:10];
    [buttonOfNext setTitle:@"下一步" forState:UIControlStateNormal];
    [buttonOfNext addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 倒计时
    __block int timeout= 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_buttonOfTime setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [_buttonOfTime setTitle:@"重新获取" forState:UIControlStateNormal];
                _buttonOfTime.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //让按钮变为不可点击的灰色
                _buttonOfTime.userInteractionEnabled = NO;
                //设置界面的按钮显示 根据自己需求设置
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [_buttonOfTime setTitle:[NSString stringWithFormat:@"%@秒后获取",strTime] forState:UIControlStateNormal];
                [_buttonOfTime setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                [UIView commitAnimations];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
- (void)reGet:(UIButton *)button
{
    NSString *url = @"http://www.wantease.com/api/index.php?act=login&op=phone_status&mobile=";
    NSString *sendmdcode = @"http://www.wantease.com/api/index.php?act=login&op=sendmbcode&mobile=";
    [GXNetWorkingParser GETWithURL:[url stringByAppendingString:_stringOfPhone] par:nil success:^(id responseObject) {
        NSLog(@"成功:%@", responseObject);
    } filed:^(NSError *error) {
        NSLog(@"失败:%@", error);
    }];
    [GXNetWorkingParser GETWithURL:[sendmdcode stringByAppendingString:_stringOfPhone] par:nil success:^(id responseObject) {
        NSLog(@"重新获取验证码成功:%@", responseObject);
    } filed:^(NSError *error) {
        NSLog(@"重新获取验证码失败:%@", error);
    }];

#if 1
    // 倒计时
    __block int timeout= 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_buttonOfTime setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [_buttonOfTime setTitle:@"重新获取" forState:UIControlStateNormal];
                _buttonOfTime.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //让按钮变为不可点击的灰色
                _buttonOfTime.userInteractionEnabled = NO;
                //设置界面的按钮显示 根据自己需求设置
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [_buttonOfTime setTitle:[NSString stringWithFormat:@"%@秒后获取",strTime] forState:UIControlStateNormal];
                [_buttonOfTime setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                [UIView commitAnimations];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);

#endif
}
- (void)next:(UIButton *)button
{
    if (_textOfCode.text.length == 4) {
        NSString *url = [NSString stringWithFormat:@"http://www.wantease.com/api/index.php?act=login&op=check_mobile_code&mobile=%@&mobile_code=%@", _stringOfPhone, _textOfCode.text];
        [GXNetWorkingParser GETWithURL:url par:nil success:^(id responseObject) {
            if ([responseObject[@"datas"] isEqualToString:@"1"]) {
                NSString *body = [NSString stringWithFormat:@"username=%@&password=%@&password_confirm=%@&mobile=%@&client=Android", _stringOfPhone, _password, _password, _stringOfPhone];
                [ZWYNetTool POST:@"http://www.wantease.com/api/index.php?act=login&op=phone_register" andBody:body andBodyStyle:ZWYBodyString andHeader:@{@"text/html": @"Content-Type",  @"utf-8" :@"charset"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
                    NSString *user = result[@"datas"][@"username"];
                    NSString *key = result[@"datas"][@"key"];
                    if (user.length != 0 && key.length != 0) {
                        MyViewController *my = [[MyViewController alloc]init];
                        NSDictionary *dic = result[@"datas"];
                        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                        //登陆成功后把用户名和密码存储到UserDefault
                        [userDefaults setObject:dic[@"username"] forKey:@"name"];
                        [userDefaults setObject:dic[@"key"] forKey:@"password"];
                        [userDefaults synchronize];
                        self.navigationController.navigationBar.hidden = NO;
                        [self.navigationController pushViewController:my animated:YES];
                        self.navigationController.navigationBar.hidden = NO;
                    }
                } andFailureBlock:^(NSError *error) {
    
                }];
            }
        } filed:^(NSError *error) {
            
        }];
    }
}

//关闭按钮
- (void)close:(UIButton *)button
{
//    [self.navigationController popViewControllerAnimated:YES];
    /** 跳转到下一个BarButtonItem */
//    self.tabBarController.selectedIndex = 0;
[self dismissViewControllerAnimated:YES completion:^{
    
}];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
